package site.koudai.cloud.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import site.koudai.cloud.annotation.DataResource;
import site.koudai.cloud.context.UserContext;
import site.koudai.cloud.entity.User;

@Component
@Data
public class DataPermissionInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(DataPermissionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod handlerMethod) {
            DataResource dataResource = handlerMethod.getMethodAnnotation(DataResource.class);
            if (dataResource == null) {
                log.info("是否需要数据权限 URI: {}, false", request.getRequestURI());
                UserContext.set("requireDataPermission", false);
                return true;
            }
            log.info("是否需要数据权限 URI: {}, true", request.getRequestURI());
            User user = (User) request.getSession().getAttribute("user");
            UserContext.set("requireDataPermission", true);
            UserContext.set("dataResourceName", dataResource.value());
            UserContext.set("userId", user.getId());
            UserContext.set("deptId", user.getDeptId());
        }
        return true;
    }

}
